Variable in JavaScript is the name of memory location. They allow us to store and reuse information in a program.
Or Variable in JavaScript is a container that contains the data.
Var is a Keyword in JavaScript, which is used to declare variables.
It is a functional-scope that means we can access it within the function it is declared.
Var is hoisted, which means it will move to the top of its scope but remains undefined until assigned a value.
function testVar(){
var name = "Shivam";
console.log(name); //Shivam (accessible inside the function)
}
testVar();
console.log(name); //Uncaught ReferenceError: name is not defined
Output:
Shivam
Uncaught ReferenceError: name is not defined
let age = 25;
console.log('let age:', age);
age = 30; // Allowed
console.log('let age after update:', age);
// let age = 35; ❌ Not allowed — SyntaxError in same scope
Output:
let age: 25
let age after update: 30
Also introduced in ES6. It is block-scoped and does not allow reassignment or redeclaration.
const country = 'India';
console.log('const country:', country);
// country = 'USA'; ❌ Not allowed — TypeError
// const country = 'UK'; ❌ Not allowed — SyntaxError
Output:
const country: India
let
and const
in modern JavaScript development.const
is preferred when the variable's value should not change.var
are hoisted but not block-scoped.